//
//  SearchController.m
//  MyTrip
//
//  Created by zhang on 15/9/8.
//  Copyright (c) 2015年 张益. All rights reserved.
//

#import "SearchController.h"
#import "AsyncGETConnection.h"
#import "SearchCell.h"
#import "CardController.h"

@interface SearchController ()<UISearchBarDelegate, UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>

@property (nonatomic, retain) UISearchBar *searchBar;
@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) NSMutableArray *searchArray;
@property (nonatomic, retain) UITextField *field;


@end

@implementation SearchController

- (void)dealloc
{
    [_searchArray release];
    [_table release];
    [_searchBar release];
    [super dealloc];
}

- (instancetype) initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        self.searchArray = [NSMutableArray array];
    }
    return self;
}

- (void)getMessage{
    [AsyncGETConnection asyncGETConnectionWithURLStr:@"http://open.qyer.com/qyer/search/hot_history?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=867436020490916&track_app_version=6.6.6&track_app_channel=91m&track_device_info=m1&track_os=Android4.4.4&app_installtime=1440130525944&lat=38.883598&lon=121.544083" parameters:nil messageBlock:^(NSData *data) {
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers error:nil];
        NSArray *search_data = [dic objectForKey:@"data"];
        [_searchArray addObjectsFromArray:search_data];
        [_table reloadData];
    }];
}


- (void)createSearchBar{
    
    self.searchBar = [[[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width / 2, 40 * OffHeight)] autorelease];
    _searchBar.barStyle = UIBarStyleDefault;
    _searchBar.placeholder = @"请输入要搜索的帖子";
    _searchBar.translucent = YES;
    _searchBar.delegate = self;
    self.field = [[self.searchBar subviews] lastObject];
    _searchBar.autocapitalizationType = UITextAutocorrectionTypeYes;
    _searchBar.keyboardType = UIKeyboardTypeDefault;
    self.navigationItem.titleView = _searchBar;
}

- (void)createCollectionView{
    
    self.table = [[[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height) style:UITableViewStylePlain] autorelease];
    _table.bounces = YES;
    _table.delegate = self;
    _table.dataSource = self;
    [_table registerClass:[SearchCell class] forCellReuseIdentifier:@"search"];
    [self.view addSubview:_table];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return _searchArray.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{

    SearchCell *cell = [tableView dequeueReusableCellWithIdentifier:@"search"];
    cell.nameLabel.text = [_searchArray objectAtIndex:indexPath.row];
    return cell;
}

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section{
    return @"热门搜索";
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
//    [self.searchBar resignFirstResponder];
    [self.searchBar setText:[_searchArray objectAtIndex:indexPath.row]];
    NSString *url = [_searchArray objectAtIndex:indexPath.row];
//    url = [url stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *urlStr = [NSString stringWithFormat:@"%@%@%@", @"http://open.qyer.com/qyer/search/index?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=867436020490916&track_app_version=6.6.6&track_app_channel=91m&track_device_info=m1&track_os=Android4.4.4&app_installtime=1440130525944&lat=38.883598&lon=121.544083&type=thread&keyword=", url, @"&count=20&page=1"];
    
    
    CardController *card = [[CardController alloc] init];
    
    card.url = urlStr;
    [self.navigationController pushViewController:card animated:YES];
    [card release];
    [_searchBar resignFirstResponder];
    
}

#pragma mark - <searchBarDelegate>
- (BOOL)searchBar:(UISearchBar *)searchBar shouldChangeTextInRange:(NSRange)range replacementText:(NSString *)text{
    return YES;
}
- (BOOL)searchBarShouldEndEditing:(UISearchBar *)searchBar{
    return YES;
}

- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSString  *str = _searchBar.text;
//    str = [str stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
    NSString *url = [NSString stringWithFormat:@"%@%@%@", @"http://open.qyer.com/qyer/search/index?client_id=qyer_android&client_secret=9fcaae8aefc4f9ac4915&v=1&track_deviceid=867436020490916&track_app_version=6.6.6&track_app_channel=91m&track_device_info=m1&track_os=Android4.4.4&app_installtime=1440130525944&lat=38.883598&lon=121.544083&type=thread&keyword=", str, @"&count=20&page=1"];
    
    CardController *card = [[CardController alloc] init];
    card.url = url;
    [self.navigationController pushViewController:card animated:YES];
    [card release];
    [_searchBar resignFirstResponder];
}

- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    NSDictionary *dic = [_searchArray objectAtIndex:section];
    NSArray *array = [dic objectForKey:@"elements"];
    return array.count;
    
}


- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    self.tabBarController.tabBar.hidden = YES;
    
}




- (void)viewDidLoad {
    [super viewDidLoad];
    [self.view setBackgroundColor:[UIColor whiteColor]];
    [self createSearchBar];
    [self createCollectionView];
    [self getMessage];
    // Do any additional setup after loading the view.
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
